//
//  SNNetworkTools.m
//  SinaVboc
//
//  Created by V on 29/11/2016.
//  Copyright © 2016 仁忄. All rights reserved.
//

#import "SNNetworkTools.h"

@protocol HTTPProxy <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end

@interface SNNetworkTools ()<HTTPProxy>

@end

@implementation SNNetworkTools

+ (instancetype)sharedTools {
    
    static SNNetworkTools *tools;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[self alloc] init];
        
        tools.responseSerializer.acceptableContentTypes = [tools.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    });
    
    return tools;
}



- (void)request:(HTTPMethod)method urlString:(NSString *)urlString parameters:(NSDictionary *)parameters finished:(void (^)(id, NSError *))finished {
    
    void(^successCallback)(NSURLSessionDataTask *task, id responseObject) = ^(NSURLSessionDataTask *task, id responseObject) {
        finished(responseObject, nil);
    };
    
    void(^failureCallback)(NSURLSessionDataTask *task, NSError *error) = ^(NSURLSessionDataTask *task, NSError *error) {
        finished(nil, error);
        NSLog(@"%@", error);
    };
    
    NSString *methodString = (method == GET ? @"GET" : @"POST");
                              
    [[self dataTaskWithHTTPMethod:methodString URLString:urlString parameters:parameters uploadProgress:nil downloadProgress:nil success:successCallback failure:failureCallback] resume];
}


@end



















































